<template>
  <div class="tag-manage">
    <div class="page-header">
      <h2>标签管理</h2>
      <p>管理衣服标签，用于分类和筛选</p>
    </div>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>标签列表</span>
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            添加标签
          </el-button>
        </div>
      </template>

      <!-- 筛选 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="filterType" placeholder="选择标签类型" clearable @change="loadTags">
              <el-option label="全部类型" value="" />
              <el-option label="风格" value="style" />
              <el-option label="季节" value="season" />
              <el-option label="场合" value="occasion" />
              <el-option label="颜色" value="color" />
              <el-option label="材质" value="material" />
              <el-option label="品牌" value="brand" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索标签名称..."
              @input="loadTags"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
        </el-row>
      </div>

      <!-- 标签表格 -->
      <el-table :data="tagList" v-loading="loading">
        <el-table-column prop="name" label="标签名称" width="150" />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="color" label="颜色" width="100">
          <template #default="{ row }">
            <div class="color-preview">
              <div
                class="color-block"
                :style="{ backgroundColor: row.color }"
              ></div>
              <span>{{ row.color }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="is_active" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editTag(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteTag(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="loadTags"
          @size-change="loadTags"
        />
      </div>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑标签' : '添加标签'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="tagForm"
        :rules="tagRules"
        label-width="100px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input v-model="tagForm.name" placeholder="请输入标签名称" />
        </el-form-item>

        <el-form-item label="标签类型" prop="type">
          <el-select v-model="tagForm.type" placeholder="选择标签类型">
            <el-option label="风格" value="style" />
            <el-option label="季节" value="season" />
            <el-option label="场合" value="occasion" />
            <el-option label="颜色" value="color" />
            <el-option label="材质" value="material" />
            <el-option label="品牌" value="brand" />
          </el-select>
        </el-form-item>

        <el-form-item label="标签颜色" prop="color">
          <div class="color-input">
            <el-color-picker v-model="tagForm.color" />
            <el-input v-model="tagForm.color" placeholder="#000000" style="width: 200px; margin-left: 10px;" />
          </div>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="tagForm.description"
            type="textarea"
            :rows="3"
            placeholder="标签描述（可选）"
          />
        </el-form-item>

        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="tagForm.is_active" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="saveTag">
          {{ saving ? '保存中...' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tagAPI } from '@/api'

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const tagList = ref([])
const formRef = ref()

const filterType = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 表单数据
const tagForm = reactive({
  id: null,
  name: '',
  type: '',
  color: '#409EFF',
  description: '',
  is_active: true
})

// 表单验证规则
const tagRules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 1, max: 20, message: '标签名称长度在1-20个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择标签类型', trigger: 'change' }
  ],
  color: [
    { required: true, message: '请选择标签颜色', trigger: 'blur' }
  ]
}

// 获取类型标签样式
const getTypeTagType = (type) => {
  const types = {
    style: 'primary',
    season: 'success',
    occasion: 'warning',
    color: 'danger',
    material: 'info',
    brand: ''
  }
  return types[type] || ''
}

// 获取类型标签文本
const getTypeLabel = (type) => {
  const labels = {
    style: '风格',
    season: '季节',
    occasion: '场合',
    color: '颜色',
    material: '材质',
    brand: '品牌'
  }
  return labels[type] || type
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载标签列表
const loadTags = async () => {
  try {
    loading.value = true

    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      type: filterType.value || undefined,
      keyword: searchKeyword.value || undefined
    }

    const response = await tagAPI.getList(params)

    if (response.code === 200) {
      tagList.value = response.data.list || []
      total.value = response.data.total || 0
    } else {
      throw new Error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  } finally {
    loading.value = false
  }
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 编辑标签
const editTag = (tag) => {
  isEdit.value = true
  Object.assign(tagForm, {
    id: tag.id,
    name: tag.name,
    type: tag.type,
    color: tag.color,
    description: tag.description || '',
    is_active: tag.is_active
  })
  dialogVisible.value = true
}

// 保存标签
const saveTag = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    saving.value = true

    let response
    if (isEdit.value) {
      response = await tagAPI.update(tagForm.id, tagForm)
    } else {
      response = await tagAPI.create(tagForm)
    }

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '标签更新成功' : '标签创建成功')
      dialogVisible.value = false
      loadTags()
    } else {
      throw new Error(response.message || '操作失败')
    }
  } catch (error) {
    console.error('保存标签失败:', error)
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    saving.value = false
  }
}

// 删除标签
const deleteTag = (tag) => {
  ElMessageBox.confirm(
    `确定要删除标签"${tag.name}"吗？删除后不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await tagAPI.delete(tag.id)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        loadTags()
      } else {
        throw new Error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除标签失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(tagForm, {
    id: null,
    name: '',
    type: '',
    color: '#409EFF',
    description: '',
    is_active: true
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 页面初始化
onMounted(() => {
  loadTags()
})
</script>

<style scoped>
.tag-manage {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-section {
  margin-bottom: 20px;
}

.color-preview {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-block {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.color-input {
  display: flex;
  align-items: center;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tag-manage {
    padding: 16px;
  }

  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>
